﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using FCMS.Data;

namespace FCMS.Extensions
{
    public static class DataExtensions
    {
        /// <summary>
        /// DataRow转实体
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="row"></param>
        /// <returns></returns>
        public static T ToEntity<T>(this DataRow row)
        {
            if (row == null)
                throw new NullReferenceException("DataRow不能为空");

            var builderEnitiy = DataRowEntityBuilder<T>.CreateBuilder(row);
            return builderEnitiy.Build(row);
        }

        /// <summary>
        /// DataTable转实体列表
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="dt"></param>
        /// <returns></returns>
        public static List<T> ToList<T>(this DataTable dt)
        {
            if (dt == null)
                throw new NullReferenceException("DataTable不能为空");

            var list = new List<T>();

            for (int i = 0; i < dt.Rows.Count; i++)
            {
                list.Add(dt.Rows[i].ToEntity<T>());
            }

            return list;
        }

        /// <summary>
        /// DataReader转实体
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="row"></param>
        /// <returns></returns>
        public static T ToEntity<T>(this IDataReader dr)
        {
            if (dr == null)
                throw new NullReferenceException("DataReader不能为空");

            var builderEnitiy = DataReaderEntityBuilder<T>.CreateBuilder(dr);
            return builderEnitiy.Build(dr);
        }
    }
}
